﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
using TomNet.IMSC.Core.Contracts.Finance;
using TomNet.IMSC.Model.DbModels.Finance;
using TomNet.IMSC.Web.Areas.Finance.Models;
using TomNet.IMSC.Web.Filters;
using TomNet.Web.Mvc;
using TomNet.Web.Mvc.Security;
using TomNet.Web.Mvc.UI;

namespace TomNet.IMSC.Web.Areas.Finance.Controllers
{
    [Description("管理-金融项")]
    [GlobalAuthorization]
    public class ItemController : BaseController
    {
        public IFinanceItemsContract ItemContract { set; get; }

        [Description("管理-金融列表")]
        public ActionResult Index()
        {
            return View();
        }
        [Description("管理-金融列表")]
        public ActionResult Index2()
        {
            return View();
        }

        [Description("管理-金融列表")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult IndexAsync(string id, int pageIndex, int pageSize, string search = "")
        {

            //string[] idsStr = ids.Split(new char[] { ',' });
            //int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
            //ItemContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new FinanceItems { IsDeleted = true });
            int mId = 0;
            if (id.IndexOf('-') > -1)
            {
                mId = Convert.ToInt32(id.Split('-')[1]);
            }
            else
            {
                if (string.IsNullOrEmpty(id))
                {
                    return View();
                }
                else
                    mId = Convert.ToInt32(id);
            }
            var entity = ItemContract.GetByKey(mId);
            int total = 0;
            List<FinanceItems> list = new List<FinanceItems>();
            list.Add(entity);
            if (entity.ParentID == 0)
            {
                var query = ItemContract.Entities.Where(x => x.ParentID == entity.Id && !x.IsDeleted);
                var objs = query.OrderBy(x => x.ShowIndex).ToList();
                list.AddRange(objs);


                foreach (FinanceItems item in objs)
                {
                    var tt = ItemContract.Entities.Where(xx => xx.ParentID == item.Id && !xx.IsDeleted).OrderBy(xx => xx.ShowIndex).ToList();
                    list.AddRange(tt);
                }

                //Expression<Func<FinanceItems, bool>> predicate = null;
                //predicate=x=>x.ParentID==
                //ItemContract.Entities.Where(xx=>xx.ParentID == query.);

            }
            else
            {
                var objs = ItemContract.Entities.Where(x => x.ParentID == entity.Id && !x.IsDeleted).OrderBy(x => x.ShowIndex).ToList();
                list.AddRange(objs);
            }
            GridData<FinanceItems> gridData = new GridData<FinanceItems>() { Total = total, Rows = list };

            return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss"); ;

            //var query = ItemContract.TrackEntities.Where(x => !x.IsDeleted);// && x.DepartmentId == depid);

            ////数据总数
            //var total = query.Count();

            ////默认给一个排序的字段
            //query = query.OrderBy(m => m.ShowIndex);

            ////分页(假如total == 0，则取消分页查询，提高性能)
            //query = total > 0 ? query.Skip((pageIndex - 1) * pageSize).Take(pageSize)
            //    : Enumerable.Empty<FinanceItems>().AsQueryable();

            //GridData<FinanceItems> gridData = new GridData<FinanceItems>() { Total = total, Rows = query.ToList() };

            ////此处采用重写后的jsonResult
            //return JsonEx(gridData, JsonRequestBehavior.AllowGet, "yyyy-MM-dd HH:mm:ss");
        }


        #region 添加金融项
        [Description("管理-添加金融项")]
        //[GlobalAuthorization]
        public ActionResult Insert(int p = 0)
        {
            initViewData(p);
            return View();
        }
        private void initViewData(int p)
        {
            List<SelectListItem> gridData = new List<SelectListItem>();
            //if (mLogin.Authority == 1)
            {
                gridData.Insert(0, new SelectListItem { Value = "0", Text = "无" });
            }
            var data = from n in ItemContract.TrackEntities.Where(x => !x.IsDeleted)// && x.ParentID == 0
                       select new SelectListItem
                       {
                           Value = n.Id + "",
                           Text = n.Name,
                           Selected = p == n.Id ? true : false
                       };

            gridData.AddRange(data);
            //initDepartAndPosition(null);
            ViewData["select_parent"] = gridData;
        }

        [Description("管理-添加金融项")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult InsertAsync(FinanceItems entity)
        {
            //所有AJAX的结果，返回统一数据格式
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = ItemContract.CheckExists(m => m.Name.Equals(entity.Name) && !m.IsDeleted);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的用户";
                }
                else
                {
                    if (entity.ParentID == 0)
                    {
                        entity.ShowIndex = ItemContract.Entities.Where(x => x.ParentID == 0).Count();
                    }

                    var count = ItemContract.Insert(entity);
                    if (count > 0)
                    {
                        result.Type = AjaxResultType.Success;
                        result.Content = "录入成功";
                        //if (entity.DepId != 0 && entity.IsLiability)
                        //{
                        //    var newuser = Contract.Entities.Where(d => d.UserName == entity.UserName).FirstOrDefault();
                        //    UpdateIsLiability(entity.DepId, newuser.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, newuser.Id);
                        //}

                        //UserInfoModel uiModel = new UserInfoModel();
                        //uiModel.Birthday = DateTime.Parse("1980-01-01");
                        //uiModel.IDNumber = "";//身份证号码
                        //uiModel.Address = "";
                        //uiModel.EMail = "";
                        //uiModel.Education = 0;
                        //uiModel.Nation = 0;//民族
                        //uiModel.PhotoId = 1;
                        //uiModel.Sex = 2;
                        //uiModel.UserId = (from m in Contract.Entities where m.UserName == entity.UserName select m.Id).FirstOrDefault();

                        //UserInfoContract.Insert(uiModel);

                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "录入失败";
                    }
                }
            }
            catch //(Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        #region 修改金融项
        [Description("管理-金融项")]
        //[GlobalAuthorization]
        public ActionResult Edit(int id)
        {

            var entity = ItemContract.GetByKey(id);
            //后台容错，有异常数据直接抛出。框架会自动跳转到错误页面。
            if (entity == null) throw new Exception("未找到该实体");

            //initDepartAndPosition(entity);
            ViewData["entity"] = entity;
            initViewData(-1);
            return View();
        }

        [Description("管理-用户修改")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditAsync(FinanceItems entity)
        {
            var result = new AjaxResult();
            try
            {
                //entity.Authority = entity.RoleId;
                //entity.RoleId = 0;

                var query = ItemContract.CheckExists(m => m.Name.Equals(entity.Name) && m.Id != entity.Id);
                if (query)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "已经存在相同的用户";
                }
                else
                {
                    ////如果选择部门不为空--默认加入考勤设置-----赵兴昌
                    //if (entity.DepId != 0)
                    //{
                    //    var dep = DepContract.GetByKey(entity.DepId);
                    //    entity.AttSetId = dep.AttSetId;
                    //}
                    //if (entity.Authority == 2) entity.IsLiability = true;

                    var count = ItemContract.Update(entity);
                    if (count > 0)
                    {
                        //if (entity.DepId != 0 && entity.IsLiability == true)
                        //{
                        //    UpdateIsLiability(entity.DepId, entity.Id);//更新部门其他人员的部门负责人状态
                        //    UpdateAuthority(entity.DepId, entity.Id);
                        //}

                        result.Type = AjaxResultType.Success;
                        result.Content = "修改成功";
                    }
                    else
                    {
                        result.Type = AjaxResultType.Error;
                        result.Content = "修改失败";
                    }
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        #endregion

        [Description("管理-删除金融项")]
        [HttpPost, AjaxOnly]
        public ActionResult DeleteAsync(string ids)
        {
            var result = new AjaxResult();
            try
            {
                string[] idsStr = ids.Split(new char[] { ',' });
                int[] idsInt = Array.ConvertAll(idsStr, id => Convert.ToInt32(id));
                ItemContract.UpdateDirect(m => idsInt.Contains(m.Id), m => new FinanceItems { IsDeleted = true });

                result.Type = AjaxResultType.Success;
                result.Content = "删除成功";
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("管理-金融项上传ICON")]
        [HttpPost, AjaxOnly]
        public ActionResult UploadImageAsync()
        {

            var oFile = Request.Files["file_data"];//.Files["txt_file"];
            var oStream = oFile.InputStream;
            //得到了文件的流对象，我们不管是用NPOI、GDI还是直接保存文件都不是问题了吧。。。。
            ImageFormat uFormat = ImageFormat.Jpeg;
            string m_saveName = "/images/icon/";
            string m_savePath = Server.MapPath(m_saveName);
            string m_exName = System.IO.Path.GetExtension(oFile.FileName);// oFile.FileName.Substring(oFile.FileName.LastIndexOf('.'));

            //switch (m_exName)
            //{
            //    case ".png":
            //        //case ".jpeg":
            //        uFormat = ImageFormat.Png;
            //        break;
            //    case ".gif":
            //        uFormat = ImageFormat.Gif;
            //        break;                
            //}
            if (Directory.Exists(m_savePath) == false)
            {
                Directory.CreateDirectory(m_savePath);
            }
            string m_fileName = DateTime.Now.ToFileTime().ToString() + m_exName;

            System.Drawing.Image img = System.Drawing.Image.FromStream(oStream);
            //img.RawFormat;
            img.Save(m_savePath + m_fileName);   //保存格式, uFormat

            string f_file = "";
            if (Request.Form["isJcrop"] == "1")
            {
                //m_fileName = "n_" + m_fileName;            
                // 生成临时图片-正方形的 
                string n_file = "n_" + m_fileName;
                ImagesHelper.imgCut(m_savePath + m_fileName, m_savePath + n_file, float.Parse(Request.Form["x"]), float.Parse(Request.Form["y"]), float.Parse(Request.Form["w"]), float.Parse(Request.Form["h"]));
                System.IO.File.Delete(m_savePath + m_fileName);

                f_file = "m_" + m_fileName;
                //-- 等比例缩放 生成新图片
                ImagesHelper.GenerateHighThumbnail(m_savePath + n_file, m_savePath + f_file, 64, 64);
                System.IO.File.Delete(m_savePath + n_file);
            }
            else
                f_file = m_fileName;


            //m_file = m_file.Replace(m_exName, "");//去掉扩展名
            //PhotoModel model = new PhotoModel()
            //{
            //    PhotoExName = oFile.FileName.Substring(oFile.FileName.LastIndexOf('.')),
            //    PhotoName = m_file,
            //    PhotoPath = m_saveName
            //};
            //PhotoContract.Insert(model);

            //var a = PhotoContract.Entities;
            //var lstOrderImport = new List<object>();
            //lstOrderImport.AddRange(PhotoContract.Entities.Where(x => x.PhotoName == m_file).ToList());


            //----------------------------------
            var result = new AjaxResult();
            try
            {
                result.Type = AjaxResultType.Success;
                result.Content = "图片上传成功";
                result.Data = f_file;
            }
            catch //(Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }
        [Description("管理-金融项上下移动")]
        [HttpPost, AjaxOnly]
        public ActionResult MoveTo(int id, int direction = 0)//string strJson
        {
            //var result = new AjaxResult();
            ////Dictionary<string, string> obj = JsonBinder<Dictionary<string, string>>.JsonToObject(strJson);
            FinanceItems item = ItemContract.GetByKey(id);
            //if (item == null)
            //{
            //    result.Type = AjaxResultType.Error;
            //    result.Content = "操作失败";
            //}
            //else
            //{
            //    item.ShowIndex += direction;
            //    ItemContract.Update(item);

            //    //----------------------------------
            //    try
            //    {
            //        result.Type = AjaxResultType.Success;
            //        result.Content = "操作成功";
            //        //result.Data = m_file;
            //    }
            //    catch (Exception ex)
            //    {
            //        result.Type = AjaxResultType.Error;
            //        result.Content = "操作失败";
            //    }
            //}
            //return JsonEx(result);
            FinanceItems nObj = new FinanceItems();
            nObj.ShowIndex = item.ShowIndex + direction;
            return ToWeb(item, nObj, 0);
        }
        private ActionResult ToWeb(FinanceItems oldObj, FinanceItems newObj, int type)
        {
            var result = new AjaxResult();
            {
                if (type == 0)
                {
                    oldObj.ShowIndex = newObj.ShowIndex;
                }
                else if (type == 1)
                {
                    oldObj.State = newObj.State;
                }
                else if (type == 2)
                {
                    oldObj.Masterplate = newObj.Masterplate;
                }
                ItemContract.Update(oldObj);

                try
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "操作成功";
                }
                catch //(Exception ex)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "操作失败";
                }
            }
            return JsonEx(result);
        }
        [Description("管理-金融项启用禁用")]
        [HttpPost, AjaxOnly]
        public ActionResult OpenOrClose(int id)//string strJson
        {
            FinanceItems item = ItemContract.GetByKey(id);

            return ToWeb(item, new FinanceItems() { State = item.State == 0 ? 1 : 0 }, 1);

        }
        [Description("管理-金融项编辑模板")]
        [HttpPost, AjaxOnly]
        public ActionResult EditMode(int id, int op)//string strJson
        {
            FinanceItems item = ItemContract.GetByKey(id);

            return ToWeb(item, new FinanceItems() { Masterplate = item.Masterplate + op }, 2);

        }


        [Description("管理-获取金融项")]
        [HttpPost, AjaxOnly, NotCollected]
        public ActionResult EditModel(int id)
        {
            var result = new AjaxResult();
            try
            {
                var query = ItemContract.GetByKey(id);
                if (query == null)
                {
                    result.Type = AjaxResultType.Error;
                    result.Content = "获取失败";
                }
                else
                {
                    result.Type = AjaxResultType.Success;
                    result.Content = "成功";
                    result.Data = query;
                }
            }
            catch
            {
                result.Type = AjaxResultType.Error;
                result.Content = "异常操作";
            }
            return JsonEx(result);
        }

        [Description("管理-金融项")]
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        [HttpPost, AjaxOnly]
        public ActionResult ExcludeStreetAsync()
        {
            var query = ItemContract.Entities.Where(m => !m.IsDeleted && m.ParentID == 0);


            Func<int, List<MyTree>> MingPian = null;

            MingPian = id =>
            {
                var basmas = ItemContract.Entities.Where(m => !m.IsDeleted && m.ParentID == id).OrderBy(x => x.ShowIndex).Select(m => new MyTree
                {
                    text = m.Name,
                    id = m.Id + "",
                    state = new
                    {
                        opened = true,//展示第一个层级下面的node 
                    },
                }).ToList(); ;
                foreach (var it in basmas)
                {
                    it.children = MingPian(int.Parse(it.id));
                }
                return basmas;
            };
            List<MyTree> ttree = MingPian(0);
            

            var data = query.OrderBy(x => x.ShowIndex).Select(m => new MyTree
            {
                text = m.Name,
                id = m.Id + "",
                state = new
                {
                    opened = true,//展示第一个层级下面的node 
                },
                //icon = (m.Authority == 1 ? "fa fa-user fa1" : (m.Authority == 2 ? "fa fa-user fa2" : "fa fa-user"))// "fa fa-user",// //
                //children = GetChildren(m.Id),
                //ItemContract.Entities.Where(a => a.ParentID.Equals(m.Id) && !a.IsDeleted)
                //.OrderBy(x => x.ShowIndex).Select(a => new
                //{
                //    text = a.Name,
                //    id = m.Id + "-" + a.Id,
                //    state = new
                //    {
                //        opened = true,//展示第一个层级下面的node 
                //    },
                //    //id = m.Value + "-" + mm.Value,
                //    children = ItemContract.Entities.Where(aa => aa.ParentID == a.Id && !a.IsDeleted)
                //    .OrderBy(x => x.ShowIndex).Select(aa => new
                //    {
                //        text = aa.Name,
                //        id = m.Id + "-" + a.Id + "-" + aa.Id,
                //    }).ToList()

                //}).ToList()
            }).ToList();


            return JsonEx(ttree);
        }

        private List<MyTree> GetChildren(int id)
        {
            var trees = ItemContract.Entities.Where(c => c.ParentID == id && !c.IsDeleted).Select(m => new MyTree
            {
                text = m.Name,
                id = m.Id + "",
                state = new
                {
                    opened = true,//展示第一个层级下面的node 
                },
                //children = GetChildren(m.Id).ToList()
            }).ToList();

            if (trees.Count() <= 0)
            {
                return (new MyTree[] { }).ToList();
            }
            else
            {
                foreach (MyTree item in trees)
                {
                    item.children = GetChildren(int.Parse(item.id));
                }

                return trees;//.ToList().Concat(query.ToList().SelectMany(t => GetChildren(t.Id)));
            }

        }


    }

}